#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, os, re, ConfigParser
from optparse import OptionParser
import demuxer
import encoder
from common import *
from logger import Logger
import globals
import config
from createmkv import createmkv

def main():
    optionparser = OptionParser(usage = "%prog [options] <file1> <file2> <file3> ...")
    availableoptions = config.settings
    for o in availableoptions:
        optionparser.add_option("--%s" % (o), dest = o, help="overwrite %s" % (o), default = availableoptions[o])
    options, fnames = optionparser.parse_args()
    fnames = expandWildcards(fnames)
    if len(fnames) == 0:
        optionparser.error("no files given")
    else:
        for f in fnames:
            if not os.path.isfile(f):
                optionparser.error("file not found: " + f)

    config.settings['audiopreset'] = 'no-encoding'
    config.settings['videopreset'] = options.videopreset

    audioEncodingOptions = config.getPresetData(config.settings['audiopreset'])
    videoEncodingOptions = config.getPresetData(config.settings['videopreset'])
    
    for fname in fnames:
        baseName = os.path.splitext(os.path.split(fname)[1])[0] # + '_enc'
        logger = Logger()
        logger.setlogfile(baseName+".batchfile")
        logger.log("#!/bin/bash\n")
        demuxer.demux(fname)
        demuxlog = demuxer.getLogName(fname)
        streams = demuxer.resolvefilenames(demuxer.getstreams(fname), demuxlog)

        for stream in streams.copy():
            s = streams[stream]
            if s['type'] in ['Video', 'video']:
                fname = s['fname']
                if config.settings['videopreset'] == 'no-encoding':
                    s['encodedfile'] = fname
                else:
                    output = fname + '.enc'
                    s['encodedfile'] = output
                    encoder.encodeVideo(fname, output, videoEncodingOptions)
            elif s['type'] in ['Audio', 'audio']:
                if s.has_key('language') and s['language'] in options.excludedaudiolanguages.split(','):
                    del streams[stream]
                else:
                    fname = s['fname']
                    if config.settings['audiopreset'] == 'no-encoding':
                        s['encodedfile'] = fname
                    else:
                        audioCodec = audioEncodingOptions['audiocodec']
                        output = fname + '.' + audioCodec #TODO
                        s['encodedfile'] = output
                        encoder.encodeAudio(fname, output, audioEncodingOptions)
            elif s['type'] in ['Subpict.', 'Subtitle', 'subtitles']:
                if s.has_key('language') and s['language'] in options.excludedsubtitlelanguages.split(','):
                    del streams[stream]

        createmkv(baseName + '.mkv', streams)

        logger.log('\n#Cleanup temporary files:\n')
        demuxer.cleanup(streams, demuxlog)
        encoder.cleanup()

        logger.log("\n#Total duration %s\n" % (formatDuration(globals.totalDuration)))
        print "\nTotal duration %s\n" % (formatDuration(globals.totalDuration))

        globals.totalDuration = 0

if __name__ == '__main__':
    main()
